/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdint.h>

#include <iostream>
#include <exception>
#include <string>

#include <boost/program_options.hpp>

#include "sgconf.h"

namespace po = boost::program_options;

int main(int argc, char **argv)
{
    // Declare the supported options.
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("login", po::value<std::string>(), "administrative login")
        ("password", po::value<std::string>(), "administrative password")
        ("host", po::value<std::string>()->default_value("localhost"), "server host")
        ("port", po::value<int>()->default_value(5555), "server port")
        ("verbose", "produce verbose output");

    po::variables_map vm;
    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
    }
    catch (std::exception & ex) {
        std::cerr << "Exception: " << ex.what() << std::endl;
        return EXIT_FAILURE;
    }
    po::notify(vm);    

    if (vm.count("help")) {
        std::cout << desc << "\n";
        return EXIT_FAILURE;
    }

    std::string login;
    if (vm.count("login")) {
        login = vm["login"].as<std::string>();
    } else {
        std::cerr << "Login was not set.\n";
        return EXIT_FAILURE;
    }

    std::string password;
    if (vm.count("password")) {
        password = vm["password"].as<std::string>();
    } else {
        std::cerr << "Password was not set.\n";
        return EXIT_FAILURE;
    }

    std::string host;
    host = vm["host"].as<std::string>();

    uint16_t port = vm["port"].as<int>();

    SGCONF conf;

    std::cout << "Connection: sgconf://" << login << ":" << password << "@" << host << ":" << port << std::endl;

    conf.SetHost(host);
    conf.SetPort(port);
    conf.SetLogin(login);
    conf.SetPassword(password);

    std::string xml(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<GetUsers/>"
    );

    if (!conf.Perform(xml)) {
        return EXIT_FAILURE;
    }

    if (!conf.GetAnswer(xml)) {
        return EXIT_FAILURE;
    }

    std::cout << xml << std::endl;

    return EXIT_SUCCESS;
}
